/* UI组件交互模块 - 表单验证功能 */

/**
 * 初始化表单验证
 */
export function initFormValidation() {
  const forms = document.querySelectorAll('form');
  
  forms.forEach(form => {
    form.addEventListener('submit', function(e) {
      // 基本必填项验证
      let isValid = true;
      const requiredFields = form.querySelectorAll('[required]');
      
      requiredFields.forEach(field => {
        if (!field.value.trim()) {
          isValid = false;
          showFieldError(field, '此字段为必填项');
        } else {
          hideFieldError(field);
        }
      });
      
      // 邮箱格式验证
      const emailFields = form.querySelectorAll('input[type="email"]');
      emailFields.forEach(field => {
        if (field.value.trim() && !isValidEmail(field.value)) {
          isValid = false;
          showFieldError(field, '请输入有效的邮箱地址');
        }
      });
      
      // 密码匹配验证
      const passwordFields = form.querySelectorAll('input[type="password"]');
      if (passwordFields.length === 2) {
        const password = passwordFields[0].value;
        const confirmPassword = passwordFields[1].value;
        
        if (password !== confirmPassword) {
          isValid = false;
          showFieldError(passwordFields[1], '两次输入的密码不匹配');
        }
      }
      
      // 如果验证失败，阻止表单提交
      if (!isValid) {
        e.preventDefault();
        
        // 滚动到第一个错误字段
        const firstError = form.querySelector('.form-group.error');
        if (firstError) {
          firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }
    });
    
    // 输入时清除错误提示
    const inputs = form.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
      input.addEventListener('input', function() {
        hideFieldError(this);
      });
    });
  });
}

/**
 * 验证邮箱格式
 */
function isValidEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
}

/**
 * 显示字段错误
 */
export function showFieldError(field, message) {
  const formGroup = field.closest('.form-group');
  if (formGroup) {
    formGroup.classList.add('error');
    
    // 查找或创建错误提示元素
    let errorElement = formGroup.querySelector('.error-message');
    if (!errorElement) {
      errorElement = document.createElement('div');
      errorElement.className = 'error-message text-danger text-sm mt-1';
      formGroup.appendChild(errorElement);
    }
    
    errorElement.textContent = message;
    
    // 添加错误动画效果
    field.style.borderColor = 'var(--color-danger)';
    field.style.transition = 'border-color 0.2s ease';
  }
}

/**
 * 隐藏字段错误
 */
export function hideFieldError(field) {
  const formGroup = field.closest('.form-group');
  if (formGroup) {
    formGroup.classList.remove('error');
    
    const errorElement = formGroup.querySelector('.error-message');
    if (errorElement) {
      errorElement.remove();
    }
    
    // 恢复正常边框色
    field.style.borderColor = '';
  }
}